<template>
  <div id="viewDiv">
    <div id="mapViewDiv">
      <button type="button" id="back" class="btn btn-primary" @click="back">返回</button>
      <div id="propertyBox" v-show="IsShowPropertyBox" class="alert alert-light" style="width:500px;height:510px">
        <div class="form-group">
          <label for="activityName">活动名称</label>
          <input type="text" class="form-control" id="activityName" v-model="UpdateActivityModel.activityName">
        </div>
        <div class="form-group">
          <label for="activityType">活动类别</label>
          <select class="form-control" id="activityType" v-model="UpdateActivityModel.activityTypeName">
            <option>大型赛会</option>
            <option>应急救助</option>
            <option>社区建设</option>
            <option>扶贫开发</option>
            <option>海外服务</option>
          </select>
        </div>
        <div class="form-group">
          <label for="activityContent">活动详情</label>
          <input type="text" class="form-control" id="activityContent" v-model="UpdateActivityModel.activityContent">
        </div>
        <div class="form-group">
          <label for="activityCompleteTime">活动结束时间</label>
          <input id="activityCompleteTime" class="form-control" type="text" v-model="UpdateActivityModel.activityCompleteTime" aria-describedby="completeTimeHelp">
          <small id="completeTimeHelp" class="form-text text-muted">例如：2023/7/4 23:00:00</small>
        </div>
        <div class="form-group">
          <label for="PCASelect">请选择省市县</label>
          <v-distpicker :province="UpdateActivityModel.province" :city="UpdateActivityModel.city" :area="UpdateActivityModel.area" @province="onChangeProvince" @city="onChangeCity" @area="onChangeArea" id="PCASelect"></v-distpicker>
        </div>
        <div class="form-group">
          <label for="DetailAddress">详细地址</label>
          <input type="text" id="DetailAddress" v-model="UpdateActivityModel.detailedAddress" class="form-control">
        </div>
        <button @click="UpdateFeatureSubmit" class="btn btn-success" v-show="!UpdateActivityModel.isCompleted">提交</button>
        <button @click="UpdateGeomerty" class="btn btn-info" v-show="IsNowGeometry">更新位置</button>
        <button @click="confirmUpdateGeometrymet" class="btn btn-secondary" v-show="confirmUpdateGeometrybtn">确定更新到此处</button>
        <button @click="CancelUpdateFeature" class="btn btn-warning" v-show="true">取消</button>
        <button @click="DeleteFeature" class="btn btn-danger">删除</button>
      </div>
    </div>
  </div>
</template>

<script>
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer.js'
import SimpleRenderer from '@arcgis/core/renderers/SimpleRenderer.js'
import PictureMarkerSymbol from '@arcgis/core/symbols/PictureMarkerSymbol.js'
import PopupTemplate from '@arcgis/core/PopupTemplate.js'
import Graphic from '@arcgis/core/Graphic.js'
export default {
  data() {
    return {
      mapview: null,
      VoluntaryGraphics: null,
      IsShowPropertyBox: false,
      ActivityID: '',
      updateGeometry: null,
      UpdateActivityModel: {
        activityID: '',
        activityName: '',
        activityContent:'',
        activityTypeName: '',
        activityCompleteTime: '',
        detailedAddress: '',
        province: '',
        city: '',
        area: '',
        isCompleted: false
      },
      layer: null,
      NowGeometry: null,
      IsNowGeometry: false,
      OBJECTID: null,
      confirmUpdateGeometry:false,
      confirmUpdateGeometrybtn:false
    }
  },
  methods: {
    back() {
      this.$router.push('../')
    },
    onChangeProvince(e) {
      this.UpdateActivityModel.province = e.value
    },
    onChangeCity(e) {
      this.UpdateActivityModel.city = e.value
    },
    onChangeArea(e) {
      this.UpdateActivityModel.area = e.value
    },
    UpdateFeatureSubmit() {
      this.axios.post('/SelectIdentity/Organization/UpdateProperty', this.UpdateActivityModel).then(res => {
        if (res.data) {
          const attribute = {
            attributes: {}
          }
          attribute.attributes['VoluntaryName'] = this.UpdateActivityModel.activityName
          attribute.attributes['VoluntaryContent'] = this.UpdateActivityModel.activityContent
          attribute.attributes['OBJECTID'] = this.updateGeometry.attributes.OBJECTID
          this.layer.applyEdits({
            updateFeatures: [attribute]
          })
          alert('更新成功')
        }
      })
    },
    CancelUpdateFeature() {
      this.IsShowPropertyBox = false
    },
    DeleteFeature() {
      const isTrueDelete = confirm('你确定要删除此要素吗')
      if (isTrueDelete) {
        this.axios
          .post('/SelectIdentity/Organization/DeleteActivity', {
            activityID: this.updateGeometry.attributes.VoluntaryActivityID
          })
          .then(res => {
            if (res.data) {
              const attribute = {
                attributes: {}
              }
              attribute.attributes['OBJECTID'] = this.updateGeometry.attributes.OBJECTID
              this.layer.applyEdits({
                deleteFeatures: [attribute]
              })
              this.IsShowPropertyBox = false
              this.mapview.popup.visible = false
            }
          })
      }
    },
    UpdateGeomerty() {
      this.axios.get(`https://apis.map.qq.com/ws/geocoder/v1/?location=${this.NowGeometry.latitude},${this.NowGeometry.longitude}&key=2EJBZ-HTQH4-PMXUU-K6H7S-RFJ3O-HEFET`).then(res => {
        const { result } = res.data
        this.UpdateActivityModel.province = result.address_component.province
        this.UpdateActivityModel.city = result.address_component.city
        this.UpdateActivityModel.area = result.address_component.district
        this.UpdateActivityModel.detailedAddress = result.address
        this.confirmUpdateGeometrybtn=true
      })
    },
    confirmUpdateGeometrymet(){      
      this.confirmUpdateGeometry=true
    }
  },
  watch:{
    confirmUpdateGeometry(newVal){      
      if(newVal){        
        if (confirm('是否要更新位置信息到此处')) {
          this.axios.post('/SelectIdentity/Organization/UpdateProperty', this.UpdateActivityModel).then(res => {
            if (res.data) {
              const updateGeometry = new Graphic({
                geometry: this.NowGeometry,
                attributes: {}
              })              
              updateGeometry.attributes['OBJECTID'] = this.OBJECTID              
              this.layer.applyEdits({
                updateFeatures: [updateGeometry]
              })
              alert('更新成功')
              this.confirmUpdateGeometrybtn=false
            }
          })
        }
      }
    }
  },
  created() {
    const map = new Map({
      basemap: 'osm-streets'
    })
    const VoluntaryActivityPointSymbol = new PictureMarkerSymbol({
      url: 'https://static.arcgis.com/images/Symbols/Shapes/BlackStarLargeB.png',
      width: '26px',
      height: '26px'
    })
    const VoluntaryActivityPointRenderer = new SimpleRenderer({
      symbol: VoluntaryActivityPointSymbol
    })
    const voluntaryActivityPopupTemplate = new PopupTemplate({
      title: '志愿活动详情',
      content: () => {
        return `
        <div class="esri-feature__fields esri-feature__content-element">
        <table class="esri-widget__table" summary="属性和值列表">
          <tbody>
            <tr>
              <th class="esri-feature__field-header">志愿名称</th>
              <td class="esri-feature__field-data">{VoluntaryName}</td>
            </tr>
          </tbody>
        </table>
      </div>
        `
      }
    })
    const layer = new FeatureLayer({
      // URL to the service
      url: 'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/VoluntaryActivityPoint/FeatureServer/0',
      outFields: ['*'],
      renderer: VoluntaryActivityPointRenderer,
      popupTemplate: voluntaryActivityPopupTemplate
    })
    let personID = JSON.parse(localStorage.getItem('Person')).organizationID
    layer.definitionExpression = 'OrganizationID=' + `'${personID}'`
    map.add(layer)
    const mapview = new MapView({
      map,
      center: [116.8, 36.55],
      zoom: 5
    })
    mapview.on('click', e => {
      let query = layer.createQuery()
      query.geometry = e.mapPoint
      component.NowGeometry = e.mapPoint
      console.log(component.NowGeometry)
      query.distance = 0.1
      query.units = 'miles'
      query.spatialRelationship = 'intersects'
      query.returnGeometry = true
      query.outFields = ['*']
      layer.queryFeatures(query).then(res => {
        try {
          this.updateGeometry = res.features[0]
          this.OBJECTID = res.features[0].attributes.OBJECTID
          component.UpdateActivityModel.activityID = res.features[0].attributes.VoluntaryActivityID
          component.axios.get(`/SelectIdentity/Organization/GetOrganitionCreateActivity?ActivityID=${component.UpdateActivityModel.activityID}`).then(res => {
            if (res.data) {
              component.IsShowPropertyBox = true
              component.UpdateActivityModel.activityName = res.data.activityName
              component.UpdateActivityModel.activityTypeName = res.data.activityTypeName
              component.UpdateActivityModel.activityCompleteTime = res.data.activityCompleteTime
              component.UpdateActivityModel.province = res.data.province
              component.UpdateActivityModel.city = res.data.city
              component.UpdateActivityModel.area = res.data.area
              component.UpdateActivityModel.detailedAddress = res.data.detailedAddress
              component.UpdateActivityModel.isCompleted = res.data.isComplete
              component.UpdateActivityModel.activityContent= res.data.activityContent
              component.IsNowGeometry = false
            }
          })
        } catch (ex) {
          this.UpdateActivityModel.isCompleted = true
          this.IsNowGeometry = true
          console.log(ex)
        }
      })
    })

    let component = this
    mapview.whenLayerView(layer).then(layerView => {
      let watchObj = layerView.watch('updating', value => {
        if (!value) {
          layerView
            .queryFeatures({
              geometry: mapview.extent,
              returnGeometry: true,
              orderByFields: ['OBJECTID']
            })
            .then(results => {
              for (let i = 0; i < results.features.length; i++) {
                let result = results.features[i]
                if (result.attributes.VoluntaryActivityID.search(component.$route.params.id) !== -1) {
                  this.mapview
                    .goTo({
                      center: result.geometry
                    })
                    .then(() => {
                      this.mapview.popup.open({
                        features: [result],
                        location: result.geometry.centroid
                      })
                      component.updateGeometry = result
                      this.OBJECTID = result.attributes.OBJECTID
                      watchObj.remove()
                      component.UpdateActivityModel.activityID = component.$route.params.id
                      component.axios.get(`/SelectIdentity/Organization/GetOrganitionCreateActivity?ActivityID=${component.$route.params.id}`).then(res => {
                        component.IsShowPropertyBox = true
                        component.UpdateActivityModel.activityName = res.data.activityName
                        component.UpdateActivityModel.activityTypeName = res.data.activityTypeName
                        component.UpdateActivityModel.activityCompleteTime = res.data.activityCompleteTime
                        component.UpdateActivityModel.province = res.data.province
                        component.UpdateActivityModel.city = res.data.city
                        component.UpdateActivityModel.area = res.data.area
                        component.UpdateActivityModel.detailedAddress = res.data.detailedAddress
                        component.UpdateActivityModel.isCompleted = res.data.isComplete
                        component.UpdateActivityModel.activityContent= res.data.activityContent
                      })
                    })
                }
              }
            })
        }
      })
    })

    this.mapview = mapview
    this.layer = layer
  },
  mounted() {
    this.mapview.container = 'mapViewDiv'
    this.mapview.ui.add('back', 'top-left')
    this.mapview.ui.add('propertyBox', 'bottom-left')
  }
}
</script>

<style lang="less" scoped>
#viewDiv {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
#mapViewDiv {
  padding: 0;
  margin: 0;
  height: 100%;
  width: 100%;
}
</style>
